
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑文章 - 我的博客</title>
    <!-- 引入Vditor的样式 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vditor@3.9.6/dist/index.css" />
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f7f7f7;
            color: #333;
        }
        .header {
            background-color: #ffffff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 15px 0;
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }
        .header h1 {
            margin: 0;
            font-size: 1.5rem;
            color: #333;
        }
        .action-buttons a, .action-buttons button {
            margin-left: 15px;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 4px;
            font-weight: 500;
            font-size: 14px;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
        }
        .view-btn {
            background-color: #4285f4;
            color: white !important;
        }
        .view-btn:hover {
            background-color: #3367d6;
        }
        .save-btn {
            background-color: #0f9d58;
            color: white !important;
        }
        .save-btn:hover {
            background-color: #0b8043;
        }
        .home-btn {
            background-color: #f1f3f4;
            color: #333 !important;
        }
        .home-btn:hover {
            background-color: #dfe1e5;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .editor-header {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .file-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        #filename {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 250px;
        }
        #vditor {
            min-height: 600px;
            margin-bottom: 20px;
        }
        .status {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        .status.success {
            background-color: #e6f4ea;
            color: #0b8043;
            display: block;
        }
        .status.error {
            background-color: #fce8e6;
            color: #d93025;
            display: block;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <h1>我的博客 - 编辑器</h1>
            <div class="action-buttons">
                <a href="/" class="home-btn">首页</a>
                <a href="#" id="view-link" class="view-btn">查看文章</a>
                <button id="saveBtn" class="save-btn">保存文章</button>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="editor-header">
            <div class="file-info">
                <label for="filename">文件名:</label>
                <input type="text" id="filename" placeholder="例如: article.md">
            </div>
            <div id="status" class="status"></div>
        </div>

        <div id="vditor"></div>
    </div>

    <!-- 引入Vditor的脚本 -->
    <script src="https://cdn.jsdelivr.net/npm/vditor@3.9.6/dist/index.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const filenameInput = document.getElementById('filename');
            const saveBtn = document.getElementById('saveBtn');
            const viewLink = document.getElementById('view-link');
            const statusEl = document.getElementById('status');

            // 从URL获取文件名
            let filename = '{{ filename }}';
            if (!filename) {
                filename = 'kk.md';
            }
            filenameInput.value = filename;

            // 更新查看链接
            viewLink.href = `/view/${filename}`;

            // 初始化Vditor编辑器
            const vditor = new Vditor('vditor', {
                height: 600,
                mode: 'ir', // 所见即所得模式
                toolbar: [
                    'headings', 'bold', 'italic', 'strike', 'link', '|',
                    'list', 'ordered-list', 'check', 'outdent', 'indent', '|',
                    'quote', 'line', 'code', 'inline-code', 'insert-before', 'insert-after', '|',
                    'upload', 'table', '|',
                    'undo', 'redo', '|',
                    'outline', 'edit-mode', 'content-theme', 'code-theme', 'export', 'fullscreen', 'preview'
                ],
                placeholder: '请输入Markdown内容...',
                cache: {
                    enable: true,
                    id: 'markdown-editor'
                },
                outline: {
                    enable: true,
                    position: 'left'
                },
                preview: {
                    hljs: {
                        enable: true,
                        lineNumber: true,
                        style: 'github'
                    },
                    markdown: {
                        toc: true
                    }
                },
                counter: {
                    enable: true
                },
                after: () => {
                    // 编辑器加载完成后获取文件内容
                    loadMarkdown(filename);
                }
            });

            // 加载Markdown文件内容
            function loadMarkdown(filename) {
                showStatus('加载中...', 'info');

                fetch(`/api/get_markdown?filename=${encodeURIComponent(filename)}`)
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(data => {
                                throw new Error(data.error || `无法加载文件，状态码: ${response.status}`);
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.content) {
                            vditor.setValue(data.content);
                            hideStatus();

                            // 从内容中提取标题设置页面标题
                            const titleMatch = data.content.match(/^# (.*?)$/m);
                            if (titleMatch && titleMatch[1]) {
                                document.title = `编辑: ${titleMatch[1]}`;
                            } else {
                                document.title = `编辑: ${filename}`;
                            }
                        } else {
                            showStatus('无法加载文件内容', 'error');
                        }
                    })
                    .catch(error => {
                        showStatus(`错误: ${error.message}`, 'error');
                        console.error('Error:', error);
                    });
            }

            // 保存Markdown内容
            function saveMarkdown() {
                const filename = filenameInput.value.trim();

                // 确保文件名不为空且有.md后缀
                if (!filename) {
                    showStatus('请输入有效的文件名', 'error');
                    return;
                }

                // 自动添加.md后缀
                const finalFilename = filename.endsWith('.md') ? filename : filename + '.md';
                filenameInput.value = finalFilename;

                // 更新查看链接
                viewLink.href = `/view/${finalFilename}`;

                showStatus('正在保存...', 'info');

                fetch('/api/save_markdown', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        filename: finalFilename,
                        content: vditor.getValue()
                    })
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(data => {
                            throw new Error(data.error || `保存失败，状态码: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        showStatus(`${finalFilename} 保存成功！`, 'success');
                        // 3秒后隐藏状态消息
                        setTimeout(hideStatus, 3000);
                    } else {
                        showStatus(`保存失败: ${data.error || '未知错误'}`, 'error');
                    }
                })
                .catch(error => {
                    showStatus(`错误: ${error.message}`, 'error');
                    console.error('Error:', error);
                });
            }

            // 显示状态消息
            function showStatus(message, type) {
                statusEl.textContent = message;
                statusEl.className = 'status';

                if (type === 'error') {
                    statusEl.classList.add('error');
                } else if (type === 'success') {
                    statusEl.classList.add('success');
                }

                statusEl.style.display = 'block';
            }

            // 隐藏状态消息
            function hideStatus() {
                statusEl.style.display = 'none';
            }

            // 文件名变化时更新查看链接
            filenameInput.addEventListener('input', function() {
                const filename = this.value.trim();
                if (filename) {
                    const finalFilename = filename.endsWith('.md') ? filename : filename + '.md';
                    viewLink.href = `/view/${finalFilename}`;
                } else {
                    viewLink.href = '/';
                }
            });

            // 保存按钮点击事件
            saveBtn.addEventListener('click', saveMarkdown);

            // 快捷键保存
            document.addEventListener('keydown', function(e) {
                // Ctrl+S 或 Command+S
                if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                    e.preventDefault();
                    saveMarkdown();
                }
            });
        });
    </script>
</body>
</html>
